package solution;

import java.util.LinkedList;

/**
 * <a href="https://www.nowcoder.com/practice/22f9d7dd89374b6c8289e44237c70447?tpId=202&&tqId=38711&rp=1&ru=/activity/oj&qru=/ta/code-written-high/question-ranking">
 * WC2 后缀表达式求值</a>
 *
 * @author or2
 * @Description 计算逆波兰式（后缀表达式）的值
 * 运算符仅包含"+","-","*"和"/"，被操作数可能是整数或其他表达式
 * @create 2021年09月12日 时间: 9:24
 */
public class EvalRPN {
    /**
     * @param tokens string字符串一维数组
     * @return int整型
     */
    public int evalRPN(String[] tokens) {
//        存放 操作数 - 栈
        LinkedList<Integer> nums = new LinkedList<>();
        for (String token : tokens) {
            Integer operand1;
            Integer operand2;
            switch (token) {
                case "+":
                    operand2 = nums.pop();
                    operand1 = nums.pop();
                    nums.push(operand1 + operand2);
                    continue;
                case "-":
                    operand2 = nums.pop();
                    operand1 = nums.pop();
                    nums.push(operand1 - operand2);
                    continue;
                case "/":
                    operand2 = nums.pop();
                    operand1 = nums.pop();
                    nums.push(operand1 / operand2);
                    continue;
                case "*":
                    operand2 = nums.pop();
                    operand1 = nums.pop();
                    nums.push(operand1 * operand2);
                    continue;
            }
            nums.push(Integer.parseInt(token));
        }

        return nums.peek();
    }
}
